﻿using System;
using System.Web.UI.WebControls;

namespace SystemX.WebControls
{
	/// <summary>
	/// calendar for a date.
	/// </summary>
	/// <remarks>
	/// http://css-tricks.com/date-display-with-sprites/
	/// </remarks>
	public class SiteCal : WebControl
	{
		public enum SiteCalTheme { 
			WhiteGray,
			BlackRed
		}
		public SiteCalTheme Theme { get; set; }
		/// <summary>
		/// Css path for the SiteCal control.Such as "Assets/css/Vivasky.SiteCal.css"
		/// </summary>
		public string CssPath { get; set; }
		public string DateStr { get; set; }
		public string CssClass { get; set; }

		private static string SpriteBlackRedTemplate {
			get
			{
				var data = "<span class=\"cal m{0} d{1}\"><span class=\"m\">{2}</span><span class=\"d\">{3}</span></span>";
				return data;
			}
		}
		private static string WhiteGrayTemplate {
			get
			{
				var data = "<abbr title=\"{0}\" class=\"postdate {1}\"><span class=\"month m-{2}\">{2}</span><span class=\"day d-{3}\">{3}</span><span class=\"year y-{4}\">{4}</span></abbr>";
				return data;
			}
		}

		protected override void Render(System.Web.UI.HtmlTextWriter writer)
		{
			var date = DateTime.Now;
			if (!string.IsNullOrEmpty(DateStr)) {
				if (!DateTime.TryParse(DateStr, out date)) {
					date = DateTime.Now;
				}
			}
			var html = string.Empty;
			if (Theme == SiteCalTheme.BlackRed) {
				html = string.Format(SpriteBlackRedTemplate,date.Month,date.Day,date.Month,date.Day);
			}
			else if (Theme == SiteCalTheme.WhiteGray) {
				html = string.Format(WhiteGrayTemplate, date.ToString(), CssClass, date.ToString("MM"), date.ToString("dd"), date.Year);
			}
			writer.Write(html);
		}
		protected override void OnPreRender(EventArgs e)
		{
			if (string.IsNullOrEmpty(CssPath))
			{
				CssPath = string.Format("Assets/css/Vivasky.SiteCal.{0}.css",Theme);
			}
			if (!CssPath.StartsWith("http://"))
			{
                CssPath = SystemX.Web.Utils.AbsoluteWebRoot + CssPath;
			}
			var cssControl = Page.FindControl("css_SiteCal");
			if (cssControl == null)
			{
				cssControl = new SiteCSS
				{
					CSSRelativeToRoot = CssPath,
					ID = "css_SiteCal"
				};
				Page.Header.Controls.Add(cssControl);
			}
			base.OnPreRender(e);
		}
	}
}
